﻿using Shop.Collect;
using Shop.Model.SpecGroupT;
using Shop.RemoteModel.GoodsSpec.Model;
using Shop.RemoteModel.SpecTemplate.Model;
using Shop.Service.Interface;
using WeDonekRpc.Helper;

namespace Shop.Service.Extend
{
    internal class SpecGroupSyncService : ISpecGroupSyncService
    {
        private readonly ISpecGroupTemplateCollect _Service;
        private readonly ISpecsTemplateCollect _Spec;
        private readonly ISpecGroupCollect _SpecGroup;
        public SpecGroupSyncService (ISpecGroupTemplateCollect service,
            ISpecsTemplateCollect specs,
            ISpecGroupCollect specGroup)
        {
            this._Spec = specs;
            this._Service = service;
            this._SpecGroup = specGroup;
        }
        public GoodsSpecGroup[] Sync (long goodsId, long categoryId)
        {
            GoodsSpecGroup[] groups = this._SpecGroup.Gets(goodsId);
            if (groups.IsNull())
            {
                SpecGroup[] items = this._GetItems(categoryId);
                if (items.Length == 0)
                {
                    return groups;
                }
                return this._SpecGroup.Sync(goodsId, items);
            }
            return groups;
        }
        private SpecGroup[] _GetItems (long categoryId)
        {
            SpecGroupTName[] glist = this._Service.Gets<SpecGroupTName>(categoryId);
            if (glist.IsNull())
            {
                return Array.Empty<SpecGroup>();
            }
            Dictionary<long, SpecTemplateItem[]> specs = this._Spec.GetSpecs(glist.ConvertAll(a => a.Id));
            return glist.ConvertAll(a =>
            {
                SpecGroup dto = new SpecGroup
                {
                    GroupName = a.GroupName
                };
                if (specs.TryGetValue(a.Id, out SpecTemplateItem[] items))
                {
                    dto.Spec = items.ConvertAll(c => new GoodsSpecItem
                    {
                        SpecIcon = c.SpecIcon,
                        SpecName = c.SpecName
                    });
                }
                return dto;
            });
        }
    }
}
